import { goodslist, goodscount } from "../../http/api"
const state = {
    list:[],
    //总数
    total:0,
    //一页显示的数量
    size:2,
    //当前的页码
    page:1
}

const getters = {
    list(state){
        return state.list
    },
    total(state){
        return state.total
    },
    size(state){
        return state.size
    },
    page(state){
        return state.page
    },
}

const mutations = {
    changeList(state,list){
        state.list=list;
    },
    changeTotal(state,total){
        state.total=total;
    },
    changeSize(state,size){
        state.size=size;
    },
    changePage(state,page){
        state.page=page;
    },

}

const actions = {
    reqListTwo(context){
        context.dispatch("reqList");
        //请求总数
        goodscount().then(res=>{
            if(res.data.code==200){
                //修改总数
                context.commit("changeTotal",res.data.list[0].total);
            }
        })
    },
    reqList(context,isAll=false){
        let params = isAll? {}:{page: context.state.page, size: context.state.size};
        goodslist(params).then(res=>{
            if(res.data.code==200){
                let arr=res.data.list ? res.data.list : []
                //如果请到的是空数组，并且不是第一页，page-1，再次请求列表(不能page--，直接修改)
                if(arr.length==0&&context.state.page>1){
                    context.commit("changePage",context.state.page-1);
                    context.dispatch("reqList");
                    return;
                }
                context.commit("changeList",arr);
            }
        })
    },
    changePage(context,page){
        context.commit("changePage",page);
        context.dispatch("reqList");
    }
    
}

export default {
    state,
    getters,
    mutations,
    actions,
    namespaced: true
}